<template>
  <div class="list">
    <ul>
      <li
        v-for="item in letters"
        :key="item"
        :ref="item"
        @click="handleLetterClick"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
      >{{ item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: '',
      timer: null
    }
  },
  computed: {
    // 创建含有字母的新数组
    letters () {
      var letters = []
      for (var key in this.cities) {
        letters.push(key)
      }
      return letters
    }
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerHTML)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearInterval(this.timer)
        }
        this.timer = setTimeout(() => {
          var startY = this.$refs['A'][0].getBoundingClientRect().top
          var index = Math.floor((e.touches[0].clientY - startY) / 20)
          var element = this.letters[index]
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', element)
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style scoped lang="less">
  @import "~styles/varibles";
.list{
  position: absolute;
  top: 1.48rem;
  bottom: 0;
  right: 0;
  overflow: hidden;
  width: 0.4rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  color: @bgColor;
  li{
    line-height: 20px;
  }
}
</style>
